package com.hanxiaozhang.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.LinkedHashMap;

/**
 * 功能描述: <br>
 * 〈权限工具类〉
 *  todo 感觉写的这么笨
 *
 * @Author:hanxiaozhang
 * @Date: 2021/3/24
 */
public class CurrentUserUtil {


    /**
     * 获取Principal
     *
     * @return
     */
    private static Object getPrincipal() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof OAuth2Authentication) {
            Object principal = ((OAuth2Authentication) authentication).getUserAuthentication().getPrincipal();
            if (principal instanceof CurrentUser) {
                return principal;
            }
            Object details = ((OAuth2Authentication) authentication).getUserAuthentication().getDetails();
            if (details instanceof LinkedHashMap && details != null) {
                principal = ((LinkedHashMap) details).get("principal");
                if (principal instanceof LinkedHashMap && principal != null) {
                    return principal;
                }
            }
        }
        return null;
    }


    /**
     * 获取当前用户id
     *
     * @return
     */
    public static Long getUserId() {

        if (getPrincipal() instanceof CurrentUser) {
            return ((CurrentUser) getPrincipal()).getUserId();
        }
        return getPrincipal() == null ? null : ((LinkedHashMap) getPrincipal()).get("userId") == null ? null : ((Integer) ((LinkedHashMap) getPrincipal()).get("userId")).longValue();
    }

    /**
     * 获取当前用户名
     *
     * @return
     */
    public static String getName() {
        if (getPrincipal() instanceof CurrentUser) {
            return ((CurrentUser) getPrincipal()).getName();
        }
        return getPrincipal() == null ? null : ((LinkedHashMap) getPrincipal()).get("name") == null ? null : (String) ((LinkedHashMap) getPrincipal()).get("name");
    }

    /**
     * 获取当前用户名称
     *
     * @return
     */
    public static String getUserName() {

        if (getPrincipal() instanceof CurrentUser) {
            return ((CurrentUser) getPrincipal()).getUsername();
        }
        return getPrincipal() == null ? null : ((LinkedHashMap) getPrincipal()).get("username") == null ? null : (String) ((LinkedHashMap) getPrincipal()).get("username");
    }

    public static void main(String[] args) {
        Object object = null;
        String str = null;

        System.out.printf((String) str);
        System.out.printf((String) object);
        System.out.printf(String.valueOf(object));

    }

}
